package com.tqz.rc.spring.cloud.registry;

import com.tqz.rc.spring.cloud.TqzRcProperties;
import com.tqz.rc.spring.cloud.TqzRcServiceManager;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.discovery.EnableDiscoveryClientImportSelector;
import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationConfiguration;
import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * <p>通过 {@link EnableDiscoveryClient} 注解导入的 {@link EnableDiscoveryClientImportSelector} 类去决定是否进行服务注册。
 * 默认情况下 {@link EnableDiscoveryClient#autoRegister()} 属性是<code>true</code>，也就是开启的，也就是会向容器中<br/>
 * 注册一个 {@link AutoServiceRegistrationConfiguration} 配置类。
 *
 * 而 {@link TqzRcServiceRegistryAutoConfiguration} 加载的条件<br/>
 * 就是在 {@link AutoServiceRegistrationConfiguration} 类加载之后才会被加载，
 * 换言之如果容器中没有 {@link AutoServiceRegistrationConfiguration} 这个类的话，
 * 那么 {@link TqzRcServiceRegistryAutoConfiguration} 也不会被加载到。
 *
 * @author tianqingzhao
 * @since 2021/9/2 14:45
 */
@Configuration
@EnableConfigurationProperties(TqzRcProperties.class)
@ConditionalOnProperty(value = "spring.cloud.service-registry.auto-registration.enabled",
        matchIfMissing = true) // 缺少该配置属性时是否可以加载。如果为true，没有该配置属性时也会正常加载；为false的时候没有该配置属性就不会加载当前类。
@AutoConfigureAfter(AutoServiceRegistrationConfiguration.class)
public class TqzRcServiceRegistryAutoConfiguration {

    @Bean
    public TqzRcServiceRegistry tqzRcServiceRegistry(
            TqzRcProperties tqzRcProperties,
            TqzRcServiceManager tqzRcServiceManager) {
        return new TqzRcServiceRegistry(tqzRcProperties, tqzRcServiceManager);
    }

    @Bean
    @ConditionalOnBean(AutoServiceRegistrationProperties.class)
    public TqzRcRegistration tqzRcRegistration(
            TqzRcProperties properties,
            ApplicationContext applicationContext) {
        return new TqzRcRegistration(properties, applicationContext);
    }

    @Bean
    @ConditionalOnBean(AutoServiceRegistrationProperties.class)
    public TqzRcAutoServiceRegistration tqzRcAutoServiceRegistration(
            TqzRcServiceRegistry serviceRegistry,
            AutoServiceRegistrationProperties autoServiceRegistrationProperties,
            TqzRcRegistration registration) {
        return new TqzRcAutoServiceRegistration(serviceRegistry,autoServiceRegistrationProperties, registration);
    }
}
